<template>
  <div>
    <render-table
      ref="table"
      :apiUrl="listOrder"
      :tableColumn="tableColumn"
      :otherConfig="otherConfig"
      :dict="dict"
      selection="multiple"
      :setupConfig="setupConfig"
      :searchConfig="searchConfig"
      :searchReset="searchReset"
      @del="del"
    >
      <!-- <template v-slot:multiple-operation="{ selectionData }">
          <el-button
            type="success"
            size="small"
            @click="handleClick2(selectionData)"
            >批量操作2</el-button
          >
        </template> -->
      <!-- <template v-slot:searchBtn="{ searchData }">
          <el-button
            size="medium"
            type="primary"
            @click="handleAdd(searchData)"
            >新增</el-button
          >
        </template> -->
      <template v-slot:searchBtn="{ searchData }">
        <!-- <el-button size="medium" type="primary" @click="handleAdd(searchData)"
          >新增</el-button
        > -->
        <el-button
          size="medium"
          type="primary"
          @click="handleImport(searchData)"
          >导入</el-button
        >
      </template>
      <template v-slot:state="{ row }">
        <el-tag
          type="primary"
          v-if="row.state === '0'"
          style="margin-left: 10px"
          >供应商报价中</el-tag
        >
        <el-tag
          type="danger"
          v-else-if="row.state === '1'"
          style="margin-left: 10px"
          >报价已截止</el-tag
        >
        <el-tag
          type="primary"
          v-else-if="row.state === '2'"
          style="margin-left: 10px"
          >送货中</el-tag
        >
        <el-tag
          type="success"
          v-else-if="row.state === '3'"
          style="margin-left: 10px"
          >订单完成</el-tag
        >
        <el-tag
          type="success"
          v-else-if="row.state === '4'"
          style="margin-left: 10px"
          >评价完成</el-tag
        >
      </template>
      <template v-slot:setup="{ row }">
        <el-button size="medium" type="text" @click="openOrderList(row)"
          >查看</el-button
        >
        <el-button
          v-if="row.state === '0'"
          size="medium"
          type="text"
          @click="openSupplyList(row)"
          >报价情况</el-button
        >
        <el-button
          v-if="row.state === '1'"
          size="medium"
          type="text"
          @click="openPricesList(row)"
          >订单比价</el-button
        >
        <el-button
          v-if="row.state === '2'"
          size="medium"
          type="text"
          @click="deliveryGoods(row)"
          >确认收货</el-button
        >
      </template>
    </render-table>
    <DialogView
      v-if="openDialog.visible"
      :dialogTitle="openDialog.dialogTitle"
      :visible="openDialog.visible"
      @submitData="submitData"
      @handleClose="handleClose"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="种类名称" prop="materialTypeName">
          <el-input
            v-model.trim="form.materialTypeName"
            placeholder="请输入种类名称"
          ></el-input>
        </el-form-item>
      </el-form>
    </DialogView>
    <DialogView
      :dialogTitle="importDialog.dialogTitle"
      :visible="importDialog.visible"
      @submitData="importData"
      @handleClose="handleClose"
      v-if="importDialog.visible"
    >
      <el-form
        ref="importForm"
        :rules="importRules"
        :model="importForm"
        label-width="120px"
      >
        <el-form-item label="订单名称" prop="name">
          <el-input
            v-model.trim="importForm.name"
            placeholder="请选择订单名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="订单招标时间" prop="timeArr">
          <el-date-picker
            v-model.trim="importForm.timeArr"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="公司类别" prop="typeIds">
          <el-cascader
            v-model="importForm.typeIds"
            :props="cascaderProps"
            collapse-tags
            placeholder="请选择公司类别"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="订单类型" prop="materialType">
          <el-select
            v-model.trim="importForm.materialType"
            placeholder="请选择订单类型"
          >
            <el-option
              v-for="item in orderType"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <el-button type="text" @click="handleExport(importForm.materialType)"
            >下载订单模板</el-button
          >
        </el-form-item>
        <div v-if="importForm.materialType === 'other'">
          <el-form-item label="交货时间" prop="deliveryTime">
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions"  v-model="importForm.deliveryTime" type="date" placeholder="选择交货时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="质保期" prop="warrantyTime">
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" v-model="importForm.warrantyTime" type="date" placeholder="选择质保期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="报价日期" prop="quotationTime">
            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :picker-options="pickerOptions" v-model="importForm.quotationTime" type="date" placeholder="选择报价日期">
            </el-date-picker>
          </el-form-item>
        </div>
        <el-form-item label="订单文件" prop="fileName">
          <div style="display: flex">
            <span>{{ importForm.fileName }}</span>
            <el-upload
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="beforeUpload"
            >
              <el-button type="text">上传文件</el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </DialogView>
    <DialogView
      v-if="supplyListDialog.visible"
      :dialogTitle="supplyListDialog.dialogTitle"
      :visible="supplyListDialog.visible"
      :popupWidth="'695px'"
      @handleClose="supplyListDialog.visible = false"
      @submitData="supplyListDialog.visible = false"
    >
      <supply-table :searchReset="supplySearchReset"></supply-table>
    </DialogView>
    <DialogView
      v-if="orderListDialog.visible"
      :dialogTitle="orderListDialog.dialogTitle"
      :visible="orderListDialog.visible"
      :popupWidth="'900px'"
      @handleClose="orderListDialog.visible = false"
      @submitData="orderListDialog.visible = false"
    >
      <orderList :searchReset="orderSearchReset"></orderList>
    </DialogView>
    <DialogView
      v-if="pricesListDialog.visible"
      :dialogTitle="pricesListDialog.dialogTitle"
      :visible="pricesListDialog.visible"
      :popupWidth="'1200px'"
      @handleClose="handleClose"
      :saveButton="false"
    >
      <pricesList
        @handleClose="handleClose"
        :orderType="pricesType"
        :searchReset="pricesSearchReset"
      ></pricesList>
    </DialogView>
  </div>
</template>
    
    <script>
import {
  listOrder,
  delOrder,
  addMaterial,
  updateMaterial,
  uploadOtherOrder,
  uploadProjectOrder,
  deliveryGood,
} from "@/api/order/api";
import { listMaterial, listType } from "@/api/purchase/api";
import orderList from "./orderList.vue";
import pricesList from "./pricesList.vue";
import SupplyTable from "./supplyTable.vue";
export default {
  components: {
    orderList,
    pricesList,
    SupplyTable,
  },
  name: "material-type",
  computed: {
    cascaderProps() {
      return {
        lazy: true,
        multiple: true,
        lazyLoad: this.lazyLoad,
        emitPath: false,
      };
    },
  },
  data() {
    return {
      pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        }, 
      pricesType: "",
      importForm: {
        materialType: "",
        name: "",
        fileName: "",
        uploadFile: {},
        timeArr: [],
        deliveryTime:'',
        warrantyTime:'',
        quotationTime:'',
      },
      orderType: [
        {
          label: "商品类",
          value: "other",
        },
        {
          label: "工程类",
          value: "project",
        },
      ],
      supplyListDialog: {
        visible: false,
        dialogTitle: "报价情况",
      },
      orderListDialog: {
        visible: false,
        dialogTitle: "订单详情信息",
      },
      importDialog: {
        visible: false,
        dialogTitle: "导入订单信息",
      },
      pricesListDialog: {
        visible: false,
        dialogTitle: "订单比价",
      },
      form: {
        materialTypeName: "",
      },
      openDialog: {
        dialogTitle: "新增",
        visible: false,
      },
      searchReset: {
        materialTypeName: "",
      },
      searchConfig: [
        {
          type: "input",
          key: "materialTypeName",
          placeholder: "请输入名称",
        },
      ],
      setupConfig: {
        del: true,
        width: 250,
      },
      dict: {},
      otherConfig: {
        list: "rows",
      },
      listOrder,
      tableColumn: [
        { prop: "orderId", label: "订单编号" },
        { prop: "orderName", label: "订单名称" },
        { prop: "purchaseName", label: "采购员" },
        { prop: "state", label: "状态", slot: true },
        { prop: "startTime", label: "订单开始时间" },
        { prop: "endTime", label: "订单截至时间" },
        { prop: "materialTypeName", label: "种类名称" },
      ],
      importRules: {
        name: [
          { required: true, message: "订单名称不能为空", trigger: "blur" },
          {
            max: 30,
            message: "订单名称不超过30个字符",
            trigger: "blur",
          },
        ],
        timeArr: [
          { required: true, message: "订单招标时间不能为空", trigger: "blur" },
        ],
        typeIds: [
          { required: true, message: "公司类别不能为空", trigger: "change" },
        ],
        materialType: [
          { required: true, message: "订单类型不能为空", trigger: "change" },
        ],
        fileName: [
          { required: true, message: "订单文件不能为空", trigger: "change" },
        ],
      },
      orderSearchReset: {
        type: "",
        orderId: "",
      },
      supplySearchReset: {
        orderId: "",
        state: "",
      },
      pricesSearchReset: {
        orderId: "",
      },
    };
  },
  created() {},
  methods: {
    //懒加载
    async lazyLoad(node, resolve) {
      let level = node.level;
      let result;
      switch (level) {
        case 0:
          let initRes = await listMaterial();
          result = initRes.rows;
          result.forEach((item) => {
            item.value = item.materialTypeId;
            item.label = item.materialTypeName;
          });
          break;
        case 1:
          let firstParams = {
            typeId: node.data.value,
          };
          let firstRes = await listType(firstParams);
          result = firstRes.data;
          result.forEach((item) => {
            item.value = item.materialId;
            item.label = item.typeName;
            item.leaf = level >= 1;
          });
          break;

        default:
          break;
      }
      resolve(result);
    },
    openSupplyList(row) {
      this.supplySearchReset.orderId = row.orderId;
      this.supplyListDialog.visible = true;
    },
    openOrderList(row) {
      this.orderSearchReset.type = row.materialTypeName;
      this.orderSearchReset.orderId = row.orderId;
      this.orderListDialog.visible = true;
    },
    openPricesList(row) {
      this.pricesSearchReset.orderId = row.orderId;
      this.pricesType = row.materialTypeName === "工程类" ? "project" : "other";
      this.pricesListDialog.visible = true;
    },
    //确认收货
    deliveryGoods(row) {
      this.$confirm("是否确认收货?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const data = {};
          data.orderId = row.orderId;
          deliveryGood(data).then(() => {
            this.$message({
              type: "success",
              message: "该订单已确认收货，请转评价",
            });
            this.$refs.table.getData();
          });
        })
        .catch(() => {});
    },
    // 表单重置
    reset() {
      this.importForm = {
        materialType: "",
        name: "",
        fileName: "",
        uploadFile: {},
        timeArr: [],
      };
      this.resetForm("importForm");
    },
    //导入订单
    importData() {
      this.$refs.importForm.validate((valid) => {
        if (valid) {
          let formData = new FormData();
          formData.append("file ", this.importForm.uploadFile);
          formData.append("typeIds ", this.importForm.typeIds);
          formData.append("orderName", this.importForm.name);
          formData.append("startTime", this.importForm.timeArr[0]);
          formData.append("endTime", this.importForm.timeArr[1]);
          const materialTypeName =
            this.importForm.materialType === "other" ? "商品类" : "工程类";
          formData.append("materialTypeName", materialTypeName);
          if (this.importForm.materialType === "other") {
          formData.append("deliveryTime", this.importForm.deliveryTime);
          formData.append("warrantyTime", this.importForm.warrantyTime);
          formData.append("quotationTime", this.importForm.quotationTime);
            uploadOtherOrder(formData).then(() => {
              this.importDialog.visible = false;
              this.$refs.table.getData();
              this.$modal.msgSuccess("成功导入订单");
              this.reset();
            });
          } else {
            uploadProjectOrder(formData).then(() => {
              this.importDialog.visible = false;
              this.$refs.table.getData();
              this.$modal.msgSuccess("成功导入订单");
              this.reset();
            });
          }
        }
      });
    },
    //上传前预操作
    beforeUpload(file, fileList) {
      console.log("file", file);
      if (!/\.(xlsx|xls|XLSX|XLS)$/.test(file.name)) {
        this.$notify.error({
          title: "错误",
          message: "上传文件只能为excel文件，且为xlsx,xls格式",
        });
      } else {
        this.importForm.fileName = file.name;
        this.importForm.uploadFile = file.raw;
      }
    },
    handleExport(type) {
      if (type) {
        this.download(
          `/file/download?type=${type}`,
          {},
          type === "other" ? "商品类报价单.xlsx" : "工程报价单.xlsx"
        );
      } else {
        this.$modal.msgError("请先选择订单类型");
      }
    },
    handleImport() {
      this.importDialog.visible = true;
      this.importDialog.dialogTitle = "导入订单信息";
    },
    del(row) {
      const orderId = row.orderId || this.ids;
      this.$modal
        .confirm('是否确认删除订单名称为"' + row.orderName + '"的数据项？')
        .then(function () {
          return delOrder(orderId);
        })
        .then(() => {
          this.$refs.table.getData();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // isSelectable(row){
    //   console.log('row',row)
    // },
    handleClose() {
      this.openDialog.visible = false;
      this.importDialog.visible = false;
      this.pricesListDialog.visible = false;
      this.$refs.table.getData();
      this.reset();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.openDialog.visible = true;
      this.openDialog.dialogTitle = "添加订单信息";
    },
    /** 提交按钮 */
    submitData() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const form = {};
          form.name = this.form.materialTypeName;
          if (this.form.materialTypeId) {
            form.id = this.form.materialTypeId;
            updateMaterial(form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.$refs.table.getData();
              this.openDialog.visible = false;
              this.form = {};
            });
          } else {
            addMaterial(form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$refs.table.getData();
              this.openDialog.visible = false;
              this.form = {};
            });
          }
        }
      });
    },
  },
};
</script>
    